// 获取按钮和容器的引用
var addRowBtn = document.getElementById('addRowBtn');
var inputContainer = document.getElementById('inputContainer');

// 定义点击事件处理函数
addRowBtn.onclick = function () {
    addRow()
};

function addRow(name, content) {
    // 创建新的行元素
    var newRow = document.createElement('div');
    newRow.className = 'layui-form-item';

    // 创建名称输入框
    var nameInput = document.createElement('input');
    nameInput.type = 'text';
    nameInput.placeholder = '名称';
    nameInput.className = 'layui-input';
    nameInput.style.marginRight = '10px';
    if (name) {
        nameInput.value = name;
    }

    // 创建链接输入框
    var linkInput = document.createElement('input');
    linkInput.type = 'text';
    linkInput.placeholder = '链接';
    linkInput.className = 'layui-input';
    linkInput.style.marginRight = '10px';
    if (content) {
        linkInput.value = content;
    }

    // 创建删除按钮
    var deleteBtn = document.createElement('button');
    deleteBtn.type = 'button';
    deleteBtn.className = 'layui-btn layui-btn-danger';
    deleteBtn.innerHTML = '删除';
    deleteBtn.onclick = function () {
        // 点击删除按钮时移除当前行
        inputContainer.removeChild(newRow);
    };

    // 将输入框和删除按钮添加到新行中
    newRow.appendChild(nameInput);
    newRow.appendChild(linkInput);
    newRow.appendChild(deleteBtn);

    // 将新行添加到容器中
    inputContainer.appendChild(newRow);
}

layui.use(['layer', 'form', 'admin', 'ax', 'formSelects', 'laydate', 'upload'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var upload = layui.upload

    laydate.render({
        elem: '#startTime',
        type: 'datetime'
    });


    var uploadInst = upload.render({
        elem: '#uploadImage'
        , url: '/upload/uploadFile'
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#showImage').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                console.log(res.msg)
                return layer.msg('上传失败');
            }
            //上传成功
            $('#showImage').attr("url_link", res.data.src);

        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText2');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });


    var formSelects = layui.formSelects;

    formSelects.data('name', 'server', {
        url: Feng.ctxPath + "/product/coinList?productId=" + Feng.getUrlParam("productId") + "&type=name"
    });

    formSelects.data('pledgeCoins', 'server', {
        url: Feng.ctxPath + "/product/coinList?productId=" + Feng.getUrlParam("productId") + "&type=pledgeCoins"
    });

    // 让当前iframe弹层高度适应
    admin.iframeAuto();


    //获取参数信息
    var ajax = new $ax(Feng.ctxPath + "/product/getData/" + Feng.getUrlParam("productId"));
    var result = ajax.start();
    form.val('productForm', result.data);

    // 设置选中的值
    formSelects.value('name', result.data.name);
    formSelects.value('pledgeCoins', result.data.pledgeCoins.split(','));

    // 设置动态添加的值
    if (result.data.productLinks != null && result.data.productLinks !== '') {
        let productLinkList = JSON.parse(result.data.productLinks);
        for (let i = 0; i < productLinkList.length; i++) {
            addRow(productLinkList[i].name, productLinkList[i].content);
        }
    }

    // 回显图片
    $('#showImage').attr("src", result.data.logoUrl);


    // 表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        var rows = inputContainer.getElementsByClassName('layui-form-item');
        var values = [];

        for (var i = 0; i < rows.length; i++) {
            var inputs = rows[i].getElementsByTagName('input');
            var name = inputs[0].value;
            var content = inputs[1].value;
            values.push({name: name, content: content});
        }

        // 将 values 数据加入到表单数据中
        data.field.productLinks = JSON.stringify(values);

        // 图片
        data.field.logoUrl = $('#showImage').attr('url_link')

        var ajax = new $ax(Feng.ctxPath + "/product/saveProduct", function (res) {
            if (res.code == 200) {
                Feng.success("修改成功！");
                //传给上个页面，刷新table用
                admin.putTempData('formOk', true);
                //关掉对话框
                admin.closeThisDialog();
            }else{
                Feng.error("添加失败！" + res.msg)
            }

        }, function (res) {
            Feng.error("添加失败！" + res.msg)
        });
        ajax.set(data.field);
        ajax.start();
    });
});
